package com.ld.data.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtils {

    /**
     * 发送post请求
     * @param url
     * @param jsonParam
     * @param connectTimeoutSeconds
     * @return
     */
    public static String sendPostConnectTimeout(String url, String jsonParam, Long connectTimeoutSeconds) {
        log.info("sendPost request url:{},jsonParam：{}", url, jsonParam);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(connectTimeoutSeconds, TimeUnit.SECONDS)
                .build();
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonParam);
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = client.newCall(request).execute();
            String responseData = Objects.requireNonNull(response.body()).string();
            //log.info("sendPost responseData: " + responseData);
            return responseData;
        } catch (Exception e) {
            log.error("sendPost error: ", e);
        }
        return "";
    }

    /**
     * 发送bodu体的Post请求
     * @param url
     * @param jsonParam
     * @return
     */
    public static String sendPost(String url, String jsonParam) {
        return sendPostConnectTimeout(url, jsonParam, 5L);
    }

    public static String setGet(String url) {
        return setGetConnectTimeout(url, 5L);
    }


    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String setGetConnectTimeout(String url, Long connectTimeoutSeconds) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(connectTimeoutSeconds, TimeUnit.SECONDS)
                .build();
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            String responseData = Objects.requireNonNull(response.body()).string();
            //log.info("setGet responseData: " + responseData);
            return responseData;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

}
